<template>
  <div class="myfavorite" style="height: 100%">
    <el-container>
      <!-- 收藏夹侧边栏设置 -->
      <el-aside width="250px">
        <el-input
          placeholder="请输入搜索关键词"
          v-model="input"
          size="small"
          clearable
          prefix-icon="el-icon-search"
          @keyup.enter.native="searchlike"
          style="width: 230px; margin-top: 20px"
        >
          <el-button
            slot="append"
            size="small"
            type="primary"
            plain
            @click="searchlike"
            >搜索</el-button
          >
        </el-input>
        <!-- 新建收藏夹设置 -->
        <div class="createNewfavorite" @click="createNewfavorite">
          <i class="el-icon-circle-plus"></i>
          <span>新建收藏夹</span>
        </div>
        <!-- 新建收藏夹弹出框 -->
        <el-dialog :visible.sync="dialogFormVisible" width="30%" top="10vh">
          <div slot="title" style="font-weight: bold; font-size: large">
            收藏夹信息
            <div
              style="
                width: 100%;
                height: 0;
                border-top: 1px solid black;
                margin-top: 10px;
              "
            ></div>
          </div>
          <el-form :model="form">
            <div style="text-align: left">
              <span style="color: red">*</span> 收藏夹名称
            </div>
            <el-input
              v-model="form.name"
              autocomplete="off"
              placeholder="收藏夹名称"
              maxlength="20"
              show-word-limit
            >
            </el-input>
            <div style="text-align: left; margin-top: 40px">简介</div>
            <el-input
              type="textarea"
              :rows="8"
              placeholder="请输入简介"
              v-model="form.textarea"
              maxlength="200"
              show-word-limit
            >
            </el-input>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="dialogNewitem">确 定</el-button>
          </div>
        </el-dialog>
        <!-- 收藏夹侧边栏 -->
        <div class="favoriteList">
          <div
            class="favoriteList-item"
            v-for="(item, index) in favoriteList"
            :key="index"
            @dblclick="changeFavoriteName(index)"
            @click="changeFavorite(item.boxroomId)"
          >
            <img
              src="@/assets/image/myself/u1124.png"
              style="height: 45px; width: 45px; float: left; margin-left: 10px"
            />
            <el-tooltip placement="bottom">
              <span>&nbsp;{{ item.boxroomName }}</span>
              <div slot="content">{{ item.intro }}</div>
            </el-tooltip>
            <!-- <span v-if="修改名字"><input type="text"></span> -->
          </div>
        </div>
        <!-- 修改收藏夹名弹出框 -->
        <el-dialog :visible.sync="dialogFormVisible2" width="30%" top="10vh">
          <div slot="title" style="font-weight: bold; font-size: large">
            修改收藏夹信息
            <div
              style="
                width: 100%;
                height: 0;
                border-top: 1px solid black;
                margin-top: 10px;
              "
            ></div>
          </div>
          <el-form :model="form2">
            <div style="text-align: left">
              <span style="color: red">*</span> 收藏夹名称
            </div>
            <el-input
              v-model="form2.name"
              autocomplete="off"
              maxlength="20"
              show-word-limit
            >
            </el-input>
            <div style="text-align: left; margin-top: 40px">简介</div>
            <el-input
              type="textarea"
              :rows="8"
              v-model="form2.textarea"
              maxlength="200"
              show-word-limit
            >
            </el-input>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible2 = false">取 消</el-button>
            <el-button type="primary" @click="dialogChangeName"
              >确 定</el-button
            >
          </div>
        </el-dialog>
      </el-aside>
      <el-container>
        <el-main>
          <div style="font-size: large; font-weight: bolder">
            <span>我的收藏：</span>
          </div>
          <!-- 不同收藏夹界面展示 -->
          <div class="favorite-item-show">
            <div
              style="
                margin-top: 10px;
                display: flex;
                width: 100%;
                height: 100%;
                flex-wrap: wrap;
                overflow: auto;
              "
            >
              <div
                v-for="(item, index) in files"
                :key="index"
                style="height: 160px; width: 130px; margin-right: 10px"
              >
                <div style="height: 60px; width: 60px; margin: 0 auto">
                  <img
                    :src="
                      require('@/assets/image/myself/' +
                        matchfileSuffixType(item.fileSuffix) +
                        '.png')
                    "
                    alt=""
                    style="width: 60px; height: 60px"
                  />
                </div>
                <div
                  style="
                    text-align: center;
                    overflow: hidden;
                    white-space: nowrap;
                    text-overflow: ellipsis;
                  "
                >
                  <span style="font-size: 12px">{{ item.fileName }}</span>
                </div>
                <div style="margin-top: 10px; height: 25px">
                  <button class="btn-preview" @click="filePreview(item.fileId)">
                    预览
                  </button>
                  <button
                    class="btn-download"
                    @click="
                      fileDownload(item.fileId, item.fileName, item.fileSuffix)
                    "
                  >
                    下载
                  </button>
                </div>
                <div
                  class="favorite-item-footer"
                  @mouseenter="mouseover(index)"
                  @mouseleave="mouseleave(index)"
                  @click="cancelFavorite(index, item.fileId, boxroomflag)"
                >
                  <img src="@/assets/image/myself/u198.png" />
                  <span class="hiddenBox">取消收藏</span>
                </div>
              </div>
            </div>
          </div>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>
<script>
import {getMyfavoriteData,
   postNewboxroom,
   postChangeboxroom,
   getChangeMyfavoriteData,
   deleteFavorite,
   getMyfavoriteSearch,
   getFileDownload} from "@/api/myself/myself";
export default {
  data() {
    return {
      input: "",
      // 单击双击效果计数器
      timer: null,
      dialogFormVisible: false,
      dialogFormVisible2: false,
      flag: "", //修改收藏夹获取的标记
      boxroomflag: "", //不同页面的标记
      userId: this.$store.getters.userId, // 公共数据
      form: {
        name: "",
        textarea: "",
      },
      form2: {
        name: "",
        textarea: "",
      },
      formLabelWidth: "100px",
      favoriteList: [
        {
          boxroomId: 1,
          boxroomName: "默认收藏夹",
          intro: "这是一个默认收藏夹",
        },
        {
          boxroomId: 2,
          boxroomName: "自定义收藏夹1",
          intro: "这是一个自定义收藏夹1",
        },
        {
          boxroomId: 3,
          boxroomName: "自定义收藏夹3",
          intro: "这是一个自定义收藏夹3",
        },
      ],
      // 直接设置点击不同的侧边栏获得不同的数组
      files: [
        {
          fileName: "帅个",
          fileId: 123,
          fileSuffix: "doc",
        },
      ],
    };
  },
  methods: {
    // 预览方法
    filePreview(fileId) {
      this.$router.push({
        path: "/docdetail",
        query: {
          id: fileId,
        },
      });
    },
    // 点击新建收藏夹
    createNewfavorite() {
      if (this.favoriteList.length >= 9) {
        window.alert("已达到最大收藏夹创建数");
        return;
      }
      this.dialogFormVisible = true;
    },
    //  新建收藏夹对话框确认按钮绑定事件
    dialogNewitem() {
      if (this.form.name === "") {
        this.$message({
          message: "收藏夹名不能为空",
          type: "warning",
        });
        return;
      }
      if (this.form.textarea === "") {
        this.form.textarea = "你的简介为空，快去添加简介吧";
      }
      // 本地添加显示
      this.favoriteList.push({
        boxroomName: this.form.name,
        intro: this.form.textarea,
      });
      // 发送添加收藏夹请求
      let formData = {
        boxroomName: this.form.name,
        intro: this.form.textarea,
        userId: this.userId,
      };
      let data = JSON.stringify(formData);
      postNewboxroom(data)
        .then((res) => {
          console.log(res);
        })
        .catch((err) => {
          console.log(err);
        });

      this.form.name = "";
      this.form.textarea = "";
      this.dialogFormVisible = false;
    },
    // 切换收藏夹界面
    changeFavorite(boxroomId) {
      clearTimeout(this.timer);
      this.boxroomflag = boxroomId;
      var that = this;
      this.timer = setTimeout(function () {
        //这里面写切换收藏夹事件的逻辑
        console.log(boxroomId);
        let data = {
          boxroomId: boxroomId,
        };
        getChangeMyfavoriteData(data)
          .then((res) => {
            console.log('获取收藏夹界面吗'+res);
            that.files = [];
            for (let i in res.data) {
              that.files.push(res.data[i]);
            }
          })
          .catch((err) => {
            console.log(err);
          });
      }, 300);
    },
    // 双击收藏夹侧边栏修改名字
    changeFavoriteName(index) {
      clearTimeout(this.timer);
      this.form2.name = this.favoriteList[index].boxroomName;
      this.form2.textarea = this.favoriteList[index].intro;
      this.dialogFormVisible2 = true;
      this.flag = index;
    },
    // 修改收藏夹名字的确认事件
    dialogChangeName() {
      if (this.form2.name === "") {
        this.$message({
          message: "收藏夹名不能为空",
          type: "warning",
        });
        return;
      }
      if (this.form2.textarea === "") {
        this.form2.textarea = "你的简介为空，快去添加简介吧";
      }
      this.favoriteList[this.flag].boxroomName = this.form2.name;
      this.favoriteList[this.flag].intro = this.form2.textarea;
      // 提交修改收藏夹名字的post请求
      let formData = {
        boxroomId: this.favoriteList[this.flag].boxroomId,
        userId: this.userId,
        boxroomName: this.form2.name,
        intro: this.form2.textarea,
      };
      let data = JSON.stringify(formData);
      postChangeboxroom(data)
        .then((res) => {
          if (res.code!=200) {
            this.$message({
              message: res.msg,
              type: 'error'
            })
          }
          console.log(res);
        })
        .catch((err) => {
          console.log(err);
        });
      this.form2.name = "";
      this.form2.textarea = "";
      this.dialogFormVisible2 = false;
    },
    //  取消收藏点击事件弹窗
    cancelFavorite(index, fileId, boxroomflag) {
      var that = this;
      this.$confirm(
        "此操作将取消收藏   " + this.files[index].fileName + "   是否继续?",
        "温馨提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          beforeClose: (action, instance, done) => {
            if (action === "confirm") {
              // 本地删除显示
              this.files.splice(index, 1);
              // 再想服务器提交删除数据的请求
              let data = {
                fileId: fileId,
                boxroomId: boxroomflag,
              };
              deleteFavorite(data)
                .then((res) => {
                  console.log(res);
                })
                .catch((err) => {
                  console.log(err);
                });
            }
            done();
          },
        }
      ).then(() => {
        this.$message({
          type: "success",
          message: "取消收藏成功!",
        });
      });
    },
    // 鼠标经过时显示取消收藏
    mouseover(index) {
      var hiddenBox = document.getElementsByClassName("hiddenBox");
      hiddenBox[index].style.display = "block";
    },
    mouseleave(index) {
      var hiddenBox = document.getElementsByClassName("hiddenBox");
      hiddenBox[index].style.display = "none";
    },
    // 下载文件
    fileDownload(fileId, fileName, fileSuffix) {
      let data = {
        userId: this.userId,
        fileId: fileId,
      };
      getFileDownload(data)
        .then((res) => {
          if (res.size === 0) {
              this.$message({
                message:'你的文件丢失了',
                type:'error'
              })
              return;
           }
          const blob = new Blob([res], { type: " application/octet-stream" });
          if ("download" in document.createElement("a")) {
            //非Ie下载
            let fileLink = document.createElement("a");
            let fileURL = window.URL.createObjectURL(blob);
            fileLink.href = fileURL;
            fileLink.setAttribute("download", fileName + "." + fileSuffix);
            document.body.appendChild(fileLink);
            fileLink.click();
            window.URL.revokeObjectURL(fileLink.href); //释放URL对象
            document.body.removeChild(fileLink);
          } else {
            navigator.msSaveBlob(blob, fileName);
          }
          console.log(res);
          if (res === "") window.alert("你下载的文件丢失了");
        })
        .catch((err) => {
          console.log(err);
        });
    },

    // 收藏界面搜索功能
    searchlike() {
      let data = {
        inputString: this.input,
        userId: this.userId,
      };
      getMyfavoriteSearch(data)
        .then((res) => {
          console.log(res);
          this.files = [];
          for (let i in res.data) {
            this.files.push(res.data[i]);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
  },
  created() {
    // 创建时加载收藏夹界面
    let data = {
      userId: this.userId,
    };
    getMyfavoriteData(data)
      .then((res) => {
        console.log(res);
        this.favoriteList = [];
        for (let i in res.data) {
          console.log(res.data[i]);
          this.favoriteList.push(res.data[i]);
        }
      })
      .catch((err) => {
        console.log(err);
      });
  },
};
</script>
<style scoped>
.el-aside {
  border-right: 1px solid rgb(121, 121, 121);
  color: #333;
  text-align: center;
  height: 598px;
  box-sizing: border-box;
  clear: both;
}

.createNewfavorite {
  width: 100%;
  height: 50px;
  line-height: 50px;
  font-size: 18px;
  font-weight: bold;
  cursor: pointer;
}

.favoriteList-item {
  width: 100%;
  height: 50px;
  line-height: 50px;
  vertical-align: top;
  text-align: left;
  font-weight: bold;
  white-space: nowrap;
  text-overflow: ellipsis;
  cursor: pointer;
  box-sizing: border-box;
}

.favoriteList-item:hover {
  background-color: rgba(0, 0, 0, 0.1);
  border-bottom: 1px solid rgb(121, 121, 121);
  border-top: 1px solid rgb(121, 121, 121);
}

.el-main {
  background-color: #e9eef3;
  color: #333;
  text-align: left;
  height: 100%;
}

.favorite-item-show {
  margin-top: 10px;
  padding: 10px;
}

.btn-preview {
  height: 25px;
  width: 40px;
  float: left;
  background-color: rgb(0, 178, 129);
  margin-left: 20px;
  border-style: none;
  font-weight: bold;
  color: aliceblue;
  border-radius: 5px;
  cursor: pointer;
}

.btn-download {
  height: 25px;
  width: 40px;
  float: right;
  background-color: rgb(22, 155, 213);
  margin-right: 20px;
  border-style: none;
  font-weight: bold;
  color: aliceblue;
  border-radius: 5px;
  cursor: pointer;
}

.favorite-item-footer {
  margin-top: 5px;
  display: flex;
  flex-direction: row;
  align-items: center;
  cursor: pointer;
}

.favorite-item-footer img {
  width: 25px;
  height: 25px;
  margin-left: 15px;
}

.hiddenBox {
  display: none;
}
</style>
